package com.wind.framework.proxy;

import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author： BeiYan
 * @Date： 2017-01-05 17:26
 * @Description：代理链
 */

public class ProxyChain {
    /**
     * 被代理的目标类
     */
    private Class<?> targetClass;

    /**
     * 被代理的目标对象
     */
    private Object targetObject;

    /**
     * 被代理的目标方法
     */
    private Method targetMethod;

    /**
     * 方法代理
     */
    private MethodProxy methodProxy;

    /**
     * 方法参数
     */
    private Object[] methodParams;

    /**
     * 代理列表
     */
    private List<Proxy> proxyList = new ArrayList<Proxy>();

    /**
     * 代理索引
     */
    private int proxyIndex = 0;

    public ProxyChain(Class<?> targetClass, Object targetObject, Method targetMethod, MethodProxy methodProxy, Object[] methodParams, List<Proxy> proxyList) {
        this.targetClass = targetClass;
        this.targetObject = targetObject;
        this.targetMethod = targetMethod;
        this.methodProxy = methodProxy;
        this.methodParams = methodParams;
        this.proxyList = proxyList;
    }

    public Class<?> getTargetClass() {
        return targetClass;
    }

    public Method getTargetMethod() {
        return targetMethod;
    }

    public Object[] getMethodParams() {
        return methodParams;
    }

    public Object doProxyChain() throws Throwable {
        Object methodResult;
        if (proxyIndex < proxyList.size()) {
            methodResult = proxyList.get(proxyIndex++).doProxy(this);
        } else {
            methodResult = methodProxy.invokeSuper(targetObject, methodParams);
        }
        return methodResult;
    }

}

